/*
    Copyright © 2014-2019 by The qTox Project Contributors

    This file is part of qTox, a Qt-based graphical interface for Tox.

    qTox is libre software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    qTox is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with qTox.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "friendlist.h"
#include "model/friend.h"
#include "persistence/settings.h"
#include "core/contactid.h"
#include "core/toxpk.h"
#include <map>
#include <algorithm>

std::map<ToxPk, Friend*> FriendList::friendList;
std::map<uint32_t, ToxPk> FriendList::id2key;

Friend* FriendList::addFriend(uint32_t friendId, const ToxPk& friendPk)
{
    auto friendChecker = friendList.find(friendPk);
    if (friendChecker != friendList.end()) {
        std::cout << "addFriend: friendPk already taken" << std::endl;
        return friendChecker->second;
    }

    Friend* newfriend = new Friend(friendId, friendPk, "");
    friendList[friendPk] = newfriend;
    id2key[friendId] = friendPk;

    return newfriend;
}

Friend* FriendList::findFriend(const ToxPk& friendPk)
{
    auto f_it = friendList.find(friendPk);
    if (f_it != friendList.end()) {
        return f_it->second;
    }

    return nullptr;
}

const ToxPk& FriendList::id2Key(uint32_t friendId)
{
    return id2key[friendId];
}

void FriendList::removeFriend(const ToxPk& friendPk, bool fake)
{
    auto f_it = friendList.find(friendPk);
    if (f_it != friendList.end()) {
        friendList.erase(f_it);
    }
}

void FriendList::clear()
{
    for (auto friendptr : friendList)
        delete friendptr.second;
    friendList.clear();
}

std::list<Friend*> FriendList::getAllFriends()
{
    std::list<Friend*> values;
    std::transform(
        friendList.begin(),
        friendList.end(),
        std::back_inserter(values),
        [](auto& kv) { return kv.second; }
    );
    return values;
}

std::string FriendList::decideNickname(const ToxPk& friendPk, const std::string& origName)
{
    Friend* f = FriendList::findFriend(friendPk);
    if (f != nullptr) {
        return f->getDisplayedName();
    } else if (!origName.empty()) {
        return origName;
    } else {
        return friendPk.toString();
    }
}
